<?php

if (!defined('CORE_PATH'))
    die('Access Denied');

class MediaManager extends Manager {

	protected $models = array("Media", "MediaCategory");
	protected $helpers = array('HTML','Request','Export');
	protected $template = "media.php";
	
    public function __construct() {
        parent::__construct('media','media_categories');
        $this->setItemClassName('Media');
        $this->setCategoryClassName('MediaCategory');
    }

    public function getMedium($id) {
        return $this->Media->findFirst( array(
			'filter' => array('Media.id' => $id)
		));
    }

    public function getMedia($options = NULL) {
		$default = array(
			'filter' => array('Published' => 1)
		);
		
		if( $options ) {
			$default = array_merge($default, $options);
		}
		
        return $this->getItems(0, NULL, $default);
    }
	
	/**
	 * Returns the first MediaCategory entry that matches the specified alias or id
	 * @return MediaCategory
	 */
	public function getCategory($alias) {
		return $this->MediaCategory->findFirst( array(
			'filter' => array(
				"OR" => array(
					"MediaCategory.Alias" => $alias,
					"MediaCategory.id" => $alias
				),
				"MediaCategory.SiteID" => SITE_ID
			)
		));		
	}
	
	public function addCategory() {
		if (!defined("IN_CMS") || !IN_CMS) {
            return;
        }
		
		$category = new MediaCategory( array(
			'SiteID' => SITE_ID,
			'Position' => $_POST['Position'],
			'Name' => $_POST['CategoryName'],
			'Alias' => $_POST['CategoryAlias'],
			'Description' => $_POST['CategoryDescription']
		));	
		
		$category->save();
		
		return $category;
	}
	
	public function updateCategory() {
		if (!defined("IN_CMS") || !IN_CMS) {
            return;
        }
		
		$category = new MediaCategory( array(
			'id' => $_POST['id'],
			'SiteID' => SITE_ID,
			'Position' => $_POST['Position'],
			'Name' => $_POST['CategoryName'],
			'Alias' => $_POST['CategoryAlias'],
			'Description' => $_POST['CategoryDescription']
		));	
		
		$category->save();
		
		return $category;
	}

    public function addMedia() {
        if (!defined("IN_CMS") || !IN_CMS) {
            return;
        }

        if (isset($_FILES['uploadFile']) && $_FILES['uploadFile']['name'] != "") {
			// update the destination folder for the media
	        $_POST['destFolder'] = kan_fix_path($_POST['destFolder']);
			
			// include file uploader
            include(CMS_PATH . 'utils/fileUpload.php');

            if ($error != "") {
                echo $error;
                return null;
            }
        }

        $media = new Media(array(
			"SiteID" => SITE_ID,
			"CategoryID" => $_POST['MediaCategory'],
            "MediaName" => $_POST['MediaName'],
            "MediaDesc" => $_POST['MediaDesc'],
            "MediaPath" => $_POST['MediaPath'],
			"MediaArtiste" => $_POST['MediaArtiste'],
			"MediaGenre" => $_POST['MediaGenre'],
			"MediaType" => $_POST['MediaType'],
            "MediaEmbedCode" => $_POST['MediaEmbedCode'],
            "MediaDuration" => $_POST['MediaDuration'],
            "MediaWidth" => $_POST['MediaWidth'],
            "MediaHeight" => $_POST['MediaHeight'],
            "MediaThumbnail" => $_POST['MediaThumbnail'],
			"DatePosted" => date("Y-m-d")
        ));

        $media->save();

        return $media;
    }

    public function updateMedia() {
        if (!defined("IN_CMS") || !IN_CMS) {
            return;
        }

        $media = new Media(array(
            "id" => $_POST['id'],
			"CategoryID" => $_POST['MediaCategory'],
            "MediaName" => $_POST['MediaName'],
            "MediaDesc" => $_POST['MediaDesc'],
			"MediaArtiste" => $_POST['MediaArtiste'],
			"MediaPath" => $_POST['MediaPath'],
			"MediaGenre" => $_POST['MediaGenre'],
			"MediaType" => $_POST['MediaType'],
            "MediaEmbedCode" => $_POST['MediaEmbedCode'],
            "MediaDuration" => $_POST['MediaDuration'],
            "MediaWidth" => $_POST['MediaWidth'],
            "MediaHeight" => $_POST['MediaHeight'],
            "MediaThumbnail" => $_POST['MediaThumbnail']
        ));


        $media->save();

        return $media;
    }
    
    /**
     * Deletes one or more media items from the database. If multiple items are to
     * deleted, the list of IDs should be passed as an array.
     * 
     * @param mixed $id
     * @return bool
     */
    public function deleteMedia($id) {
        if (!defined("IN_CMS") || !IN_CMS) {
            return false;
        }
        
        if( !is_int($id) && !is_array($id) ) {
            trigger_error("The supplied parameters must be an integer or an array of ints");
            return;
        }
        
        // make the $id parameter an array if an int to prevent the implode function
        // from failing in the "find" filter operation
        if( is_int($id) ) {
            $id = array($id);
        }
        
        $media = $this->find('Media', array(
            'filter' => array('id IN' => $id)
        ));
        
        foreach($media as $m) {
            $file = kan_fix_path($m->getPath());
            
            if( file_exists($file) ) {
                @unlink($file);
            }
        }
        
        // delete the items from the database
        $this->Media->deleteAll(array('id IN' => $ids));
    }
	
	public function downloadMedia($id_or_alias) {
		$medium = $this->getMedium($id_or_alias);
		
		if( $medium ) {
			$path = kan_fix_path($medium->getData('MediaPath'));
			$this->Export->downloadFile($path, $medium->getData('MediaName'));	
		}
	}

	/**
	 * @override overrides the super render implementation
	 */
	public function render() {
		
		$category = NULL;
        $media = NULL;

        if (isset($_GET['category'])) {
            $category = $this->getCategory(kan_clean_input($_GET['category']));
        }

        if (isset($_GET['id'])) {
            $media = $this->getMedium(kan_clean_input($_GET['id']));
            
        } else if( isset($_GET['file']) ) {
			$this->downloadMedia( $_GET['file'] );
            exit;
			
		} else if (isset($_GET['url'])) {
            // the url parameters
            $parts = explode("/", kan_get_parameter('url'));

            // if the url parameters contains more than two parameters then the url is
            // valid and the article can be loaded. e.g. news/article-title
            if (count($parts) >= 1 && !empty($parts[0]) && $parts[0] != "file") {
                $category = $this->getCategory(kan_clean_input($parts[0]));
            }

            if (count($parts) >= 2 && !empty($parts[1])) {
                $media = $this->getMedium(kan_clean_input($parts[1]));
            }
			
			if (count($parts) >= 2 && !empty($parts[1])) {
                // we are attempting a download
                if ($parts[0] == "file") {
					// part[1] is expected to be the ID or alias of the media file
                    $this->downloadMedia( $parts[1] );
                    exit;
                } else {
                    $media = $this->getMedium(kan_clean_input($parts[1]));
                }
            }
        }

        $this->set("category", $category);
        $this->set("media", $media);

        parent::render();
	}
}
?>